#!/bin/bash

# 显示帮助信息的函数
show_help() {
  echo "Usage: $0 <namespace> [-f] [-g] [-r] [-c] [-d] [-e] [-h]"
  echo "  -f  实时跟踪日志"
  echo "  -g  过滤日志中的'Caused by'"
  echo "  -r  重启这个namespace下面的deploy"
  echo "  -c  检查健康状态"
  echo "  -d  描述 Pod 信息"
  echo "  -e  进入 Pod 的 shell"
  echo "  -h  显示帮助信息"
  exit 0
}

# 检查是否提供了命名空间参数或帮助参数
if [ "$#" -eq 0 ]; then
  show_help
fi

# 检查是否提供了命名空间参数
if [ "$1" == "-h" ]; then
  show_help
elif [ -z "$1" ];then
  echo "Usage: $0 <namespace> [-f] [-g] [-r] [-c] [-d] [-e] [-h]"
  exit 1
fi

NAMESPACE=$1
FOLLOW_LOGS=false
GREP_CAUSED_BY=false
RESTART_DEPLOYMENTS=false
CHECK_HEALTH=false
DESCRIBE_POD=false
EXEC_POD=false

# 解析其他参数
shift
while getopts "fgrcdeh" opt; do
  case $opt in
    f)
      FOLLOW_LOGS=true
      ;;
    g)
      GREP_CAUSED_BY=true
      ;;
    r)
      RESTART_DEPLOYMENTS=true
      ;;
    c)
      CHECK_HEALTH=true
      ;;
    d)
      DESCRIBE_POD=true
      ;;
    e)
      EXEC_POD=true
      ;;
    h)
      show_help
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      exit 1
      ;;
  esac
done

# 重启命名空间下的所有 deployments
if [ "$RESTART_DEPLOYMENTS" = true ]; then
  echo "Restarting all deployments in namespace: $NAMESPACE"
  kubectl rollout restart deployment -n $NAMESPACE
  exit 0
fi

# 健康检查
if [ "$CHECK_HEALTH" = true ]; then
  # 获取 Ingress Hosts
  HOSTS=$(kubectl get ingress -n $NAMESPACE -o jsonpath='{.items[0].spec.rules[0].host}')
  
  if [ -z "$HOSTS" ]; then
    echo "No ingress hosts found in namespace $NAMESPACE"
    exit 1
  fi

  echo "Checking health for namespace: $NAMESPACE"

  # 定义要检查的 URL 列表
  URLS=(
    "http://${HOSTS}"
    "http://${HOSTS}/${NAMESPACE}/actuator/healthcheck"
    "http://${HOSTS}/dap/actuator/check"
  )

  # 顺序执行健康检查
  for URL in "${URLS[@]}"; do
    RESPONSE=$(curl -s $URL)
    if [ -n "$RESPONSE" ]; then
      if echo "$RESPONSE" | grep -q "404 Not Found"; then
        continue
      fi
      echo "Health check succeeded for $URL"
      echo "$RESPONSE"|jq .
      exit 0
    fi
  done

  # 如果所有检查都没有返回值
  echo "All health checks failed for host: $HOSTS"
  exit 1
fi

# 获取 AGE 最小的 Pod 名称
POD_NAME=$(kubectl get pods -n $NAMESPACE --sort-by=.metadata.creationTimestamp -o jsonpath='{.items[-1].metadata.name}')

# 检查是否找到了 Pod
if [ -z "$POD_NAME" ]; then
  echo "No pods found in namespace $NAMESPACE"
  exit 1
fi

# 描述 Pod 信息
if [ "$DESCRIBE_POD" = true ]; then
  kubectl describe pods $POD_NAME -n $NAMESPACE
  exit 0
fi

# 进入 Pod 的 shell
if [ "$EXEC_POD" = true ]; then
  kubectl exec -it $POD_NAME -n $NAMESPACE sh
  exit 0
fi

# 跟踪 Pod 日志
echo "Following logs for pod: $POD_NAME in namespace: $NAMESPACE"

if [ "$FOLLOW_LOGS" = true ] && [ "$GREP_CAUSED_BY" = true ]; then
  kubectl logs -f $POD_NAME -n $NAMESPACE | grep "Caused by"
elif [ "$GREP_CAUSED_BY" = true ]; then
  kubectl logs $POD_NAME -n $NAMESPACE | grep "Caused by"
elif [ "$FOLLOW_LOGS" = true ]; then
  kubectl logs -f $POD_NAME -n $NAMESPACE
else
  kubectl logs $POD_NAME -n $NAMESPACE
fi